﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace WxServices.Services
{
    public class CleanXmlFormatter : XmlMediaTypeFormatter
    {
        public CleanXmlFormatter()
        {
            UseXmlSerializer = true;
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,TransportContext transportContext)
        {
            try
            {

                var task = Task.Factory.StartNew(() =>
                {
                    ToXml(type,value, writeStream);
                });

                return task;
            }
            catch (Exception)
            {
                return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
            }
        }

        //string[] skipxmlns = { "xsi", "xsd", "" };
        void ToXml(Type type,object obj, Stream writeStream)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);
            System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(type);
            XDocument xd = new XDocument();
            using (var xdw = xd.CreateWriter())
            {
                xs.Serialize(xdw, obj, ns);
            }
            //var xmlstr= xd.ToString();
            //Console.WriteLine(xmlstr);
            //xd.Save(Console.Out);
            //xd.Root.Attributes().Where(v =>  v.Name.LocalName).Remove();
            xd.Root.RemoveAttributes();
            StreamWriter sw = new StreamWriter(writeStream,System.Text.Encoding.UTF8);
            sw.Write(xd.ToString());
        }

    }
}